import json
from random import randint

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from utils.aliyunSMS import Sms_send


class SmsCodeSend(View):
    def get(self, request, mobile):
        image_code_id = request.GET.get('image_code_id')
        image_code = request.GET.get('image_code')
        if not all([image_code, image_code_id]):
            # 如果没有验证码
            return JsonResponse({'code': 400, 'errmsg': "请填写图片验证码"})

        # 验证图片验证码
        redis_cli = get_redis_connection("code")
        redis_image_code = redis_cli.get(image_code_id)
        if redis_image_code is None:
            return JsonResponse({'code': 400, 'errmsg': "图片验证码过期"})
        # 获取到redis中存入的后删除数据
        try:
            redis_cli.delete(image_code_id)
        except Exception:
            print('图片验证码删除成功')
        if redis_image_code.decode().lower() != image_code.lower():
            # 如果验证码错误
            return JsonResponse({'code': 400, 'errmsg': "图片验证码错误"})

        sms_code = randint(100000, 900000)  # 设置随机验证码

        redis_cli_sms = get_redis_connection("sms_code")
        # 1 创建管道连接
        pl = redis_cli_sms.pipeline()
        user_mobile_flag = redis_cli_sms.get("send_flag_%s" % mobile)
        if user_mobile_flag:
            return JsonResponse({'code': 400, 'errmsg': "操作过于频繁，请稍后再试"})

        sms_send = Sms_send()
        resp_sms = sms_send.sms_aliyun(mobile, str(sms_code))  # 参1：手机号 参2：内容
        if json.loads(resp_sms).get('Message') == 'OK':
            # 将Redis请求添加到队列
            # 2 保存短信验证码 到redis  key的格式 sms_手机号
            pl.setex("sms_%s" % mobile, 300, sms_code)
            # 3 保存"send_flag_手机号"的值
            pl.setex("send_flag_%s" % mobile, 60, 1)
            # 执行请求
            pl.execute()
            print('短信验证码发送成功：{}'.format(str(sms_code)))
        else:
            print('短信验证码发送失败：{}'.format(resp_sms))

        return JsonResponse({'code': 0, 'errmsg': "send sms code ok"})
